package edu.sctu.wangfuxin.day20150616;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by user06 on 2015/6/16.
 */
public class Test_URL {

    public void getURL(String path){
        int count = 0;
        byte[] buffer = new byte[1024];
        try {
            URL url = new URL(path);
            try {
                InputStream ipputStream =  url.openStream();
                while((count = ipputStream.read(buffer))!=-1){
                    System.out.println(new String(buffer,0,count));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    public void getURL1(String path){
        int count = 0;
        byte[] buffer = new byte[1024];
        try {
            URL url = new URL(path);
            try {
                URLConnection urlConnection =  url.openConnection();
                urlConnection.connect();
                InputStream inputStream =  urlConnection.getInputStream();
                while((count = inputStream.read(buffer))!=-1){
                    System.out.println(new String(buffer,0,count,"gb2312"));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

    }


    public void testURLConnection() throws Exception{
        URL url = new URL("http://www.baidu.com/");
        HttpURLConnection urlcon = (HttpURLConnection)url.openConnection();
        urlcon.connect();
        InputStream is = urlcon.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
        StringBuffer stringBuffer = new StringBuffer();
        String l;
        while ((l = bufferedReader.readLine())!=null){
            stringBuffer.append(l).append("\n");
        }
        System.out.println(stringBuffer.toString());
    }


    public void aaaa(String path) throws Exception{
        byte[] bytes = new byte[1024];
        URL url = new URL(path);
        int count = 0;
        HttpURLConnection urlcon = (HttpURLConnection)url.openConnection();
        InputStream is = urlcon.getInputStream();
        FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\\TestIO\\testURL2.txt"));
        while((count = is.read(bytes))!=-1){
            fileOutputStream.write(bytes);
        }

    }


    public static void main(String[] args) throws Exception{
        Test_URL test_url = new Test_URL();
        //test_url.getURL("http://www.baidu.com/");
        test_url.getURL1("http://api.ii.com.cn/goods/apprec");
//        long s = System.currentTimeMillis();
//        System.out.println(s);
       // test_url.testURLConnection();
        //test_url.aaaa("http://www.baidu.com/");
    }
}
